package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.VideoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoManager {

    @Reference
    private VideoService videoService;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Reference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "tanhua-video", key = "#userId+'_'+#pageNum+'_'+#pageSize")
    public PageBeanVo findVideo(Integer pageNum, Integer pageSize, Long userId) { // 用户、第一页、第二页、第三页

        System.out.println("查询mysql+mongoDB。。。。。");

        // 1.调用rpc查询
        PageBeanVo pageBeanVo = videoService.findVideoByPage(pageNum, pageSize, userId);

        // 2.封装vo
        List<VideoVo> voList = new ArrayList<>();
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                // 获取发布小视频的用户id
                Long videoUserId = video.getUserId();

                // 查询该用户详情
                UserInfo userInfo = userInfoService.findById(videoUserId);

                // 创建并封装vo
                VideoVo videoVo = new VideoVo();
                BeanUtil.copyProperties(userInfo, videoVo);// 用户信息
                BeanUtil.copyProperties(video, videoVo);// 视频信息
                // 封装其他补充字段
                videoVo.setCover(video.getPicUrl()); // 视频封面
                videoVo.setSignature(video.getText()); // 视频文字
                videoVo.setHasLiked(0);// 是否点赞

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, userId, videoUserId))) {
                    videoVo.setHasFocus(1); // 关注
                } else {
                    videoVo.setHasFocus(0); // 未关注
                }

                // 添加voList
                voList.add(videoVo);

            }
        }

        // 3.返回分页对象
        pageBeanVo.setItems(voList);

        return pageBeanVo;
    }

    @CacheEvict(value = "tanhua-video",key = "#userId+'_*'")
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile, Long userId) throws IOException {
        // 1.将封面上传oss
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        // 2.将视频上传fastDFS
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        // 3.封装video实体
        Video video = new Video();
        video.setUserId(userId);
        video.setText("左右手一个慢动作~~~");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setCreated(System.currentTimeMillis());

        // 4.调用rpc完成发布
        videoService.saveVideo(video);
    }

    public void saveFocusUser(Long focusUserId) {
        // 1.获取登录userId
        Long userId = UserHolder.get().getId();
        // 2.封装实体
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId); // 登录人
        focusUser.setFocusUserId(focusUserId); // 视频发布人
        focusUser.setCreated(System.currentTimeMillis());// 关注时间
        // 3.调用rpc保存
        focusUserService.saveFocusUser(focusUser);
        // 4.将关注标记存储redis
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");
    }

    public void deleteFocusUser(Long focusUserId) {
        // 1.获取登录userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc删除
        focusUserService.deleteFocusUser(focusUserId, userId);
        // 3.将关注标记从redis中删除
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));
    }
}
